package vip.meet.interceptor;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;

import java.sql.Connection;
import java.util.Properties;

@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})})
public class ReplicateConnection implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Connection connection = (Connection) invocation.getArgs()[0];
        StatementHandler handler = (StatementHandler) invocation.getTarget();
        String sql = handler.getBoundSql().getSql();
        if (sql != null && sql.toLowerCase().startsWith("select")) {
            connection.setReadOnly(true);
//            System.err.println("set slave");
//            System.err.println(sql);
        } else {
            connection.setReadOnly(false);
//            System.err.println("set master");
//            System.err.println(sql);
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
//        System.out.println(properties.getProperty("test"));
    }
}
